package com.hu.ta.assignment6.beans;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.mail.Header;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class EmailContent {

	private String type = "";
	private String subject = "";
	private String main = "";
	private String from = "";
	private List<String> tokens = null;
	private int numPictures = 0;
	private int htmlTags = 0;
	private boolean upperCase = false;

	public EmailContent() {

	}

	public void addHeader(Header h) {
		if (h.getName().equals("Content-Type")) {
			type = h.getValue();
		} else if (h.getName().equals("From")) {
			from = h.getValue();
		}
		// TODO: Absender mit einbringen
	}

	private static boolean isUpperCase(String str) {
		int lower = str.length();
		int num = 0;
		for (char c : str.toCharArray()) {
			if (Character.isLetter(c)) {
				if (Character.isUpperCase(c)) {
					num++;
					lower--;
				}
			}
		}

		return (lower / (float) num < 0.01);
	}

	public void addSubject(String subject) {
		this.subject = subject;
	}

	public void addContent(Object content) {
		if (content.getClass().getName().equals("java.lang.String")) {
			upperCase = isUpperCase((String) content);
			this.main = ((String) content).toLowerCase();
			if (type.contains("html")) {
				Document d = Jsoup.parse(this.main);
				try {
					this.main = d.body().text();
					Elements e = d.select("img");
					numPictures = e.size();
					e = d.select("*");
					htmlTags = e.size();
					// e = d.select("div");
					// htmlTags += e.size();
				} catch (NullPointerException e) {

				}
			}
		}
		// TODO: anderer Content (MimeContent)
	}

	public List<String> getWords() {
		if (tokens == null) {
			tokens = new ArrayList<String>();
			StringTokenizer tokenizer = new StringTokenizer(subject + " " + main,
					" +\n+\r+\t+.+,+-+");
			while (tokenizer.hasMoreTokens()) {
				tokens.add(tokenizer.nextToken());
			}
		}
		return tokens;
	}

	public String getContent() {
		return main;
	}

	public String getSender() {
		return from;
	}

	public String getSubject() {
		return subject;
	}

	public String getType() {
		return type;
	}

	public int getNumPictures() {
		return numPictures;
	}

	public int getNumHTMLTags() {
		return htmlTags;
	}

	public boolean isAllUpperCase() {
		return upperCase;
	}
}
